/**
 * 泛娱区块链 - Main
 * http://menger.me
 * @大梦
 */

'use strict';

import React from 'react';
import {View, StyleSheet, NetInfo, Linking, AppState, DeviceEventEmitter, BackHandler} from 'react-native';
import SplashScreen from 'react-native-splash-screen'
import DeviceInfo from 'react-native-device-info';
import JPushModule from 'jpush-react-native'
import JShareModule from 'jshare-react-native';
import XPay from 'react-native-puti-pay';
import Navigation from '../router/Navigation';
import Orientation from 'react-native-orientation'
import SpinnerLoading from '../component/common/SpinnerLoading';
import {getDeviceInfo} from '../util/Tool';
import {observer, inject} from 'mobx-react';
import RouterHelper from '../router/RouterHelper';

@inject('appStore', 'loginStore')
@observer
class Main extends React.Component {

    constructor(props) {
        super(props);
        this.state = {loading: false}
    }

    componentDidMount() {
        this._initSetting() // 初始化设置，先调用
        this._addPushListener(); // 通知,先调用
        // this._handleLoginState() // 处理登陆状态
        setTimeout(this._handleLoginState, 300);
        this._addDeviceInfo() // 设备信息
        this._addLinkingListener() // 处理外部跳转链接
        this._addNetworkListener() // 网络状态
        this._addAppStateListener() // app前台还是后台
        this._addLoadingListener()
        this._addBackHandlerListener();
    };

    _addBackHandlerListener = () => {
        BackHandler.addEventListener('hardwareBackPress', () => {
            //这里的路由信息是你自己项目中的，通过这个原理，我们还是可以提示一些其他信息，比如表单没填写完整等等
            // console.log('back----->', RouterHelper.navigation);
            //写入当前页面的路由信息
            if (RouterHelper.navigation.state.routeName === 'Tab' || RouterHelper.navigation.state.routeName === 'Login') {
                if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {//按第二次的时候，记录的时间+2000 >= 当前时间就可以退出
                    //最近2秒内按过back键，可以退出应用。
                    BackHandler.exitApp();//退出整个应用
                    return false
                }
                this.lastBackPressed = Date.now();//按第一次的时候，记录时间
                ToastManager.show('再按一次退出应用');
                return true;
            } else {
                RouterHelper.goBack();
                return true;
            }
        });
    };

    componentWillUnmount() {
        // this._removeLinkingListener()
        // this._removeNetworkListener()
        // this._removePushListener()
        // this._removeAppStateListener()
    };

    _initSetting = () => {
        if (__IOS__) {
            // 启动极光分享 ios需要
            JShareModule.setup()
        } else {
            // 仅仅在安卓调用
            JPushModule.initPush();
            JPushModule.notifyJSDidLoad(resultCode => {
                if (resultCode === StatusCode.SUCCESS_CODE) {
                }
            })
        }
        // debug模式
        JShareModule.setDebug({enable: __DEV__})
        //设置微信ID
        XPay.setWxId(Constants.WEI_XIN_APPID)
        //设置支付宝URL Schemes
        XPay.setAlipayScheme(Constants.ALIPAY_SCHME)
        // 显示竖屏
        Orientation.lockToPortrait()
    };

    _handleLoginState = async () => {
        const {loginStore} = this.props;
        const localRes = await StorageManager.load(Constants.USER_INFO_KEY);
        // console.log('localRes------>',localRes);
        if (localRes.data) {
            const result = await loginStore.getUserData(localRes.data.user_id);
            if (result.code === StatusCode.SUCCESS_CODE){
                // console.log('进入主页');
                RouterHelper.reset('', 'Tab');
            }
        }

        SplashScreen.hide()
    };

    _addPushListener = () => {
        __ANDROID__ && JPushModule.addReceiveCustomMsgListener(map => {
            // 自定义消息
            // console.log('extras: ' + map.extras)
        })

        JPushModule.addReceiveNotificationListener(map => {
            // 接收推送事件     并且点击推送（ios9及以下）需要判断系统版本
            // console.log('alertContent: ', map.alertContent)
            // console.log('extras: ', map.extras)
        })

        JPushModule.addReceiveOpenNotificationListener(map => {
            // 点击推送事件，iOS10及以上
            // console.log('Opening notification!')
            // console.log('map.extra: ' + map.extras)
        })

        JPushModule.addGetRegistrationIdListener(registrationId => {
            // 设备注册成功
            // console.log('Device register succeed, registrationId ' + registrationId)
        })
    };

    _removePushListener = () => {
        JPushModule.removeReceiveCustomMsgListener()
        JPushModule.removeReceiveNotificationListener()
        JPushModule.removeReceiveOpenNotificationListener()
        JPushModule.removeGetRegistrationIdListener()
        JPushModule.clearAllNotifications()
    };

    _addAppStateListener = () => {
        const {appStore} = this.props
        AppState.addEventListener('change', (state) => {
            appStore.changeAppState(state)
        })
    };

    _removeAppStateListener = () => {
        AppState.removeEventListener('change', () => {
        })
    };

    _addLinkingListener = () => {
        Linking.addEventListener('url', (data) => {
            // console.log('_addLinkingListener', data)
        })
    };

    _removeLinkingListener = () => {
        Linking.removeEventListener('url', () => {
        })
    };

    _addNetworkListener = () => {
        const {appStore} = this.props
        NetInfo.addEventListener('connectionChange', ({type, effectiveType}) => {
            // console.log('connectionInfo-->', type, effectiveType)
            appStore.changeNetworkState(type)
        });
    };

    _removeNetworkListener = () => {
        NetInfo.removeEventListener('connectionChange', () => {
        });
    };

    _addDeviceInfo = async () => {
        const {appStore} = this.props
        const info = getDeviceInfo()
        // const ip = await DeviceInfo.getIPAddress() ios上不可用，有可能是私有方法
        const batteryLevel = await DeviceInfo.getBatteryLevel() // 电池的电量，模拟器返回-1
        appStore.setDeviceInfo({...info, batteryLevel})
        // console.log(info, batteryLevel)
    };

    _addLoadingListener = () => {
        DeviceEventEmitter.addListener(Constants.APPLOADING, (loading) => {
            if (this.state.loading !== loading) {
                this.setState({loading})
            }
        })
    };

    render() {
        const {loading} = this.state
        return (
            <View style={styles.container}>
                <Navigation/>
                <SpinnerLoading isVisible={loading}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    }
});

export default Main